/*
 * @Project Name: spring-boot
 * @File Name: UserService
 * @Package Name: com.hhly.spring.boot.cache
 * @Date: 2017/12/13 17:52
 * @Creator: linshixing-1199
 * @line------------------------------
 * @修改人:
 * @修改时间:
 * @修改内容:
 */

package com.sm.shoplook.service.system.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sm.shoplook.constant.ResultMessage;
import com.sm.shoplook.dao.mapper.system.PermissionMapper;
import com.sm.shoplook.domain.system.Permission;
import com.sm.shoplook.service.system.PermissionService;
import com.sm.shoplook.vo.base.ApiResult;
import com.sm.shoplook.vo.system.permission.PermissionMenuRespVo;

/**
 * @author chenpy-1072
 * @desc UserService
 * @date 2017/12/13 17:52
 * @see
 */
@Service
public class PermissionServiceImpl implements PermissionService {

	private static final Logger LOGGER = LoggerFactory.getLogger(PermissionServiceImpl.class);
	@Autowired
	private PermissionMapper permissionMapper;

	@Override
	public ApiResult<List<Permission>> selectPermissionsByRoleCode(String roleCode) {
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, permissionMapper.selectPermissionsByRoleCode(roleCode));
	}

	@Override
	public ApiResult<List<PermissionMenuRespVo>> selectAllPermissions() {
		List<PermissionMenuRespVo> permissionFirstLevels = permissionMapper.selectFirstLevel();
		if (CollectionUtils.isEmpty(permissionFirstLevels)) {
			return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, new ArrayList<PermissionMenuRespVo>());
		}
		permissionFirstLevels.forEach(permissionFirstLevel -> {
			String menuCode = permissionFirstLevel.getMenuCode();
			List<PermissionMenuRespVo> permissionSecondLevels = permissionMapper.selectSecondLevel(menuCode);
			if (CollectionUtils.isNotEmpty(permissionSecondLevels)) {
				permissionFirstLevel.setChildMenus(permissionSecondLevels);
				permissionSecondLevels.forEach(permissionSecondLevel -> {
					List<Permission> permissions = permissionMapper
							.selectThreeLevel(permissionSecondLevel.getMenuCode());
					permissionSecondLevel.setPermissions(permissions);
				});
			}
		});
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, permissionFirstLevels);
	}
}
